package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.aliyun.iot20180120.Client;
import com.aliyun.iot20180120.models.*;
import com.fasterxml.jackson.databind.ser.Serializers;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageResponse;
import com.zzyl.base.ResponseResult;
import com.zzyl.constant.CacheConstants;
import com.zzyl.dto.DeviceDto;
import com.zzyl.dto.DevicePageQueryDto;
import com.zzyl.entity.Device;
import com.zzyl.enums.BasicEnum;
import com.zzyl.enums.DeviceLocationTypeEnum;
import com.zzyl.enums.DevicePhysicalLocationTypeEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.DeviceMapper;
import com.zzyl.properties.AliIoTConfigProperties;
import com.zzyl.service.DeviceService;
import com.zzyl.vo.DeviceVo;
import com.zzyl.vo.ProductVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description DeviceServiceImpl
 * @Author lyh
 * @Date 2024-10-30
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class DeviceServiceImpl implements DeviceService {
    private final AliIoTConfigProperties aliIoTConfigProperties;
    private final Client client;
    private final StringRedisTemplate redisTemplate;
    private final DeviceMapper deviceMapper;
    /**
     * 从物联网平台同步产品列表
     */
    @Override
    public void syncProductList() {
        //调用查询IOT所有产品列表：QueryProductList
        //1.构建查询产品列表请求对象
        QueryProductListRequest request = new QueryProductListRequest();
        request.setCurrentPage(1);
        request.setPageSize(200);
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        //2.client执行查询产品列表接口调用，返回响应对象
        QueryProductListResponse response=null;
        try {
             response = client.queryProductList(request);
        } catch (Exception e) {
            //3.处理远程接口调用异常，结束应用程序
            e.printStackTrace();
            throw new BaseException(BasicEnum.IOT_LIST_PRODUCT_ERROR);
        }
        //4.获取响应体success判断是否调用成功，失败抛出异常，结束程序
         if(!response.getBody().getSuccess()){
             log.info("从物联网平台同步产品列表异常"+response.getBody().getErrorMessage());
             throw new BaseException(BasicEnum.IOT_LIST_PRODUCT_ERROR);
         }

        //5.获取响应体 body.data.list.productInfo集合
        List<QueryProductListResponseBody.QueryProductListResponseBodyDataListProductInfo> productInfo = response.getBody().getData().getList().getProductInfo();
        //6.将productInfo集合转换为List<ProductVo>
        //List<ProductVo> productVos = BeanUtil.copyToList(productInfo, ProductVo.class); //效率低
        List<ProductVo> productVoList = productInfo.stream().map(product -> {
            ProductVo productVo = new ProductVo();
            productVo.setProductKey(product.getProductKey());
            productVo.setProductName(product.getProductName());
            return productVo;
        }).collect(Collectors.toList());

        //7.写入缓存
        redisTemplate.opsForValue().set(CacheConstants.ALL_PRODUCT_KEY, JSONUtil.toJsonStr(productVoList));
    }

    @Override
    public List<ProductVo> allProduct() {
        //从Redis缓存中取出数据
        String s = redisTemplate.opsForValue().get(CacheConstants.ALL_PRODUCT_KEY);
        //不为空转为List<ProductVo>
        if(StrUtil.isNotBlank(s)){
           return  JSONUtil.toList(s,ProductVo.class);
        }
        //为空直接返回null
        return null;
    }

    @Override
    public void registerDevice(DeviceDto deviceDto) {
        //1.查询数据库注册的设备英文名是否重复
        //根据设备英文名查询设备对应数量
      Long count= deviceMapper.countDeviceByDeviceName(deviceDto.getDeviceName());

        //数量大于0，说明已存在，抛出异常结束程序
        if(count>0){
            log.info("新增设备失败，失败原因:{}","设备名重复");
            throw new BaseException(BasicEnum.IOT_REGISTER_DEVICE_ERROR);
        }
        //2.远程调用IOT注册设备RegisterDevice接口，并且获取生成的设备id
        //从deviceDto中获取注册设备请求对象
        RegisterDeviceRequest registerDeviceRequest = deviceDto.getRegisterDeviceRequest();
        //注册设备请求对象封装IotInstanceId属性
        registerDeviceRequest.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        //远程调用注册设备接口获取返回RegisterDeviceResponse对象
        RegisterDeviceResponse registerDeviceResponse=null;
        try {
            registerDeviceResponse = client.registerDevice(registerDeviceRequest);
        } catch (Exception e) {
            //捕获远程调用可能发生的异常,抛出友好提示异常
            log.info("新增设备失败，失败原因:{}","远程调用失败");
            throw new BaseException(BasicEnum.IOT_REGISTER_DEVICE_ERROR);
        }

        //获取RegisterDeviceResponse对象返回数据success判断是否调用成功，失败抛出友好提示异常
          if(!registerDeviceResponse.getBody().getSuccess()){
              log.info("新增设备失败，失败原因:{}","远程调用返回失败");
              throw new BaseException(BasicEnum.IOT_REGISTER_DEVICE_ERROR);
          }
        //接口调用成功，获取生成的设备id（响应体data.IotId），封装到deviceDto
         String iotId = registerDeviceResponse.getBody().getData().getIotId();
          deviceDto.setIotId(iotId);
        //3.deviceDto转换为device对象
        Device device = BeanUtil.toBean(deviceDto, Device.class);
        //4.补全产品的名字，远程调用查询产品QueryProduct接口
        QueryProductRequest queryProductRequest = new QueryProductRequest();
        //构建查询产品请求对象，封装属性ProductKey和IotInstanceId
        queryProductRequest.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        queryProductRequest.setProductKey(device.getProductKey());
        //远程调用注册设备接口获取返回QueryProductResponse对象
        QueryProductResponse queryProductResponse=null;
        try {
            queryProductResponse = client.queryProduct(queryProductRequest);
        } catch (Exception e) {
            //捕获远程调用可能发生的异常,抛出友好提示异常
            log.info("新增设备失败，失败原因:{}","查询设备远程调用失败");
            throw new BaseException(BasicEnum.IOT_REGISTER_DEVICE_ERROR);
        }
        if(!queryProductResponse.getBody().getSuccess()){
            //获取QueryProductResponse对象返回数据success判断是否调用成功，失败抛出友好提示异常
            log.info("新增设备失败，失败原因:{}","查询设备远程调用返回失败");
            throw new BaseException(BasicEnum.IOT_REGISTER_DEVICE_ERROR);
        }

        //接口调用成功，获取产品名字（响应体data.ProductName），封装到device
        device.setProductName(queryProductResponse.getBody().getData().getProductName());
        //5.判断设备位置绑定类型是否为随身设备，如果是设置物理班绑定类型（physicalLocationType）为-1
        if(DeviceLocationTypeEnum.PORTABLE_DEVICE.getOrdinal().equals(device.getLocationType())){
            device.setPhysicalLocationType(DevicePhysicalLocationTypeEnum.ELDER.getOrdinal());
        }
        //6.将设备保存到数据库
        //补全是否包含门禁，默认设置为0
        device.setHaveEntranceGuard(0);
        //调用mapper保存
        try {
            deviceMapper.insertSelective(device);
        } catch (Exception e) {
            //捕获异常，远程调用删除IOT设备接口（DeleteDevice）
            DeleteDeviceRequest deleteDeviceRequest = new DeleteDeviceRequest();
            //构建查删除IOT设备请求对象，封装属性IotInstanceId和IotId
            deleteDeviceRequest.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
            deleteDeviceRequest.setIotId(iotId);
            //远程调用删除设备接口
            DeleteDeviceResponse deleteDeviceResponse=null;
            try {
                deleteDeviceResponse = client.deleteDevice(deleteDeviceRequest);
            } catch (Exception e1) {
                //捕获删除设备远程接口调用发生异常（如果其企业中删除失败，会记录日志，通知管理员（邮件或手机短信））
                log.info("删除设备失败，失败原因:{}","删除设备远程调用失败");
            }
            if(!deleteDeviceResponse.getBody().getSuccess()) {
                //获取QDeleteDeviceResponse对象返回数据success判断是否调用成功，失败抛出友好提示异常（如果其企业中删除失败，会记录日志，通知管理员（邮件或手机短信））
                log.info("删除设备失败，失败原因:{}","删除设备远程调用返回失败");
            }
            //抛出异常结束，提示友好信息
            throw new BaseException(BasicEnum.IOT_REGISTER_DEVICE_ERROR);
        }

    }

    @Override
    public PageResponse<DeviceVo> pageQueryDevice(DevicePageQueryDto devicePageQueryDto) {
        PageHelper.startPage(devicePageQueryDto.getPageNum(),devicePageQueryDto.getPageSize());
        Page<DeviceVo> page=deviceMapper.pageQueryDevice(devicePageQueryDto);
        return PageResponse.of(page,DeviceVo.class);
    }

    @Override
    public DeviceVo queryDeviceDetail(QueryDeviceDetailRequest request) {
        //先从数据库获取数据
        DeviceVo deviceVo= deviceMapper.queryDetailByIotId(request.getIotId());
        if(deviceVo==null){
            throw new RuntimeException("该设置不存在");
        }
        //远程调用queryDeviceDetail
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        QueryDeviceDetailResponse queryDeviceDetailResponse=null;
        try {
            queryDeviceDetailResponse = client.queryDeviceDetail(request);
        } catch (Exception e) {
           log.info("远程调用发生异常:异常原因:{}",e.getMessage());
        }
        if(!queryDeviceDetailResponse.getBody().getSuccess()){
            log.info("远程调用发生异常:异常原因:{}",queryDeviceDetailResponse.getBody().getErrorMessage());
        }
        if(queryDeviceDetailResponse.getBody().getSuccess()){
            QueryDeviceDetailResponseBody.QueryDeviceDetailResponseBodyData data = queryDeviceDetailResponse.getBody().getData();
            //将远程结果赋值给deviceVo 忽略空值
            BeanUtil.copyProperties(data,deviceVo, CopyOptions.create().ignoreNullValue());
        }

        return deviceVo;
    }

    @Override
    public ResponseResult queryDevicePropertyStatus(QueryDevicePropertyStatusRequest request) {
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        QueryDevicePropertyStatusResponse response=null;
        try {
            response = client.queryDevicePropertyStatus(request);
        } catch (Exception e) {
            throw new BaseException(BasicEnum.IOT_QUERY_DEVICE_PROPERTY_STATUS_ERROR);
        }
        if(!response.getBody().getSuccess()){
            throw new BaseException(BasicEnum.IOT_QUERY_DEVICE_PROPERTY_STATUS_ERROR);
        }

        return ResponseResult.success(response.getBody().getData());
    }

    @Override
    public ResponseResult queryThingModelPublished(QueryThingModelPublishedRequest request) {
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        QueryThingModelPublishedResponse response = null;
        try {
            response=client.queryThingModelPublished(request);
        } catch (Exception e) {
            throw new RuntimeException("查看指定产品的已发布物模型中的功能定义详情");
        }
        if(!response.getBody().getSuccess()){
            throw new RuntimeException("查看指定产品的已发布物模型中的功能定义详情");
        }
        return ResponseResult.success(response.getBody().getData());
    }

    @Override
    public void updateDevice(DeviceDto deviceDto) {
       if(deviceDto==null){
           throw new BaseException(BasicEnum.DEVICE_NOT_EXIST);
       }
        //   阿里云对应接口方法：client.batchUpdateDeviceNickname(request)接口中只提供了批量修改接口
        BatchUpdateDeviceNicknameRequest request = new BatchUpdateDeviceNicknameRequest();
        RegisterDeviceRequest request1 = deviceDto.getRegisterDeviceRequest();
        Device device = BeanUtil.toBean(deviceDto, Device.class);
        List<BatchUpdateDeviceNicknameRequest.BatchUpdateDeviceNicknameRequestDeviceNicknameInfo> list=new ArrayList<>();
        BatchUpdateDeviceNicknameRequest.BatchUpdateDeviceNicknameRequestDeviceNicknameInfo info = BeanUtil.toBean(request1, BatchUpdateDeviceNicknameRequest.BatchUpdateDeviceNicknameRequestDeviceNicknameInfo.class);
        list.add(info);
        request.setDeviceNicknameInfo(list);
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        BatchUpdateDeviceNicknameResponse response=null;
        try {
            response = client.batchUpdateDeviceNickname(request);
        } catch (Exception e) {
           throw new RuntimeException("修改设备失败");
        }
        if(!response.getBody().getSuccess()){
            throw new RuntimeException("修改设备失败");
        }
        //判断设备位置绑定类型是否为随身设备，如果是设置物理班绑定类型（physicalLocationType）为-1
        if(DeviceLocationTypeEnum.PORTABLE_DEVICE.getOrdinal().equals(device.getLocationType())){
            device.setPhysicalLocationType(DevicePhysicalLocationTypeEnum.ELDER.getOrdinal());
        }
        //4.补全产品的名字，远程调用查询产品QueryProduct接口
        QueryProductRequest queryProductRequest = new QueryProductRequest();
        //构建查询产品请求对象，封装属性ProductKey和IotInstanceId
        queryProductRequest.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        queryProductRequest.setProductKey(device.getProductKey());
        //远程调用注册设备接口获取返回QueryProductResponse对象
        QueryProductResponse queryProductResponse=null;
        try {
            queryProductResponse = client.queryProduct(queryProductRequest);
        } catch (Exception e) {
            //捕获远程调用可能发生的异常,抛出友好提示异常
            log.info("修改设备失败，失败原因:{}","查询设备远程调用失败");
            throw new RuntimeException("查询设备远程调用返回失败");
        }
        if(!queryProductResponse.getBody().getSuccess()){
            //获取QueryProductResponse对象返回数据success判断是否调用成功，失败抛出友好提示异常
            log.info("修改设备失败，失败原因:{}","查询设备远程调用返回失败");
            throw new RuntimeException("查询设备远程调用返回失败");
        }

        //接口调用成功，获取产品名字（响应体data.ProductName），封装到device
        device.setProductName(queryProductResponse.getBody().getData().getProductName());
        device.setHaveEntranceGuard(0);
        deviceMapper.updateByPrimaryKeySelective(device);
    }

    @Override
    public void deleteDevice(DeleteDeviceRequest request) {
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        DeleteDeviceResponse response=null;
        try {
            response = client.deleteDevice(request);
        } catch (Exception e) {
            throw new BaseException(BasicEnum.IOT_DELETE_DEVICE_ERROR);
        }
        if(!response.getBody().getSuccess()){
            throw new BaseException(BasicEnum.IOT_DELETE_DEVICE_ERROR);
        }
        deviceMapper.deleteByIotId(request.getIotId());

    }
}
